﻿using System.Xml;

namespace RulesEngine.Configuration
{
    public class RulesEngineConfigManagerProvider<TCandidate>
    {
        public RulesEngineConfigManagerProvider()
        {
        }

        public RulesEngine<TCandidate> GetRulesEngine(string configKey)
        {
            XmlDocument xmlDoc = ConfigManager.GetConfigXml(configKey);

            RulesEngineConfigurationXmlProvider<TCandidate> xmlProvider = new RulesEngineConfigurationXmlProvider<TCandidate>();
            xmlProvider.Load(xmlDoc);
            RulesEngine<TCandidate> engine = xmlProvider.GetRulesEngine();

            return engine;
        }

        public TRulesEngine GetRulesEngine<TRulesEngine>(string configKey)
            where TRulesEngine : RulesEngine<TCandidate>, new()
        {
            XmlDocument xmlDoc = ConfigManager.GetConfigXml(configKey);

            var xmlProvider = new RulesEngineConfigurationXmlProvider<TCandidate>();
            xmlProvider.Load(xmlDoc);
            var engine = xmlProvider.GetRulesEngine<TRulesEngine>();

            return engine;
        }

        public TRulesEngine GetRulesEngine<TRulesEngine>(string configKey, TRulesEngine rulesEngine)
            where TRulesEngine : RulesEngine<TCandidate>
        {
            XmlDocument xmlDoc = ConfigManager.GetConfigXml(configKey);

            var xmlProvider = new RulesEngineConfigurationXmlProvider<TCandidate>();
            xmlProvider.Load(xmlDoc);
            var engine = xmlProvider.GetRulesEngine(rulesEngine);

            return engine;
        }

        public TRulesEngine GetRulesEngine<TRulesEngine>(string configKey, RulesEngineConfigurationXmlProvider<TCandidate> xmlProvider)
            where TRulesEngine : RulesEngine<TCandidate>, new()
        {
            XmlDocument xmlDoc = ConfigManager.GetConfigXml(configKey);
            xmlProvider.Load(xmlDoc);
            var engine = xmlProvider.GetRulesEngine<TRulesEngine>();

            return engine;
        }
    }
}